package ybt.vueelement.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import ybt.vueelement.filter.JWTAuthenticationFilter;
import ybt.vueelement.service.SysUserService;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
	private SysUserService userService;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
		//auth.inMemoryAuthentication().withUser("aaa").password("{noop}12345").roles("ADMIN","DIY");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
		http.headers().frameOptions().disable();    //解决iframe与安全器兼容性问题
		http.cors();
		http.formLogin().loginPage("/login").permitAll()
		.successForwardUrl("/loginSucc").permitAll()
		.failureUrl("/loginFail").permitAll();
		http.logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSucc") .permitAll();
		http.authorizeRequests().antMatchers("/student/download").permitAll();
		http.authorizeRequests().anyRequest().authenticated()
			.and()
			.addFilter(new JWTAuthenticationFilter(authenticationManager()));    //除此之外的都必须通过请求验证才能访问
		http
			.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler())
			.authenticationEntryPoint(new MyAuthenticationEntryPoint());
		
	}
	@Bean
	CorsConfigurationSource corsConfigurationSource() {
		final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
		return source;
	}
	
	
}
